//
//  MineViewController.m
//  quxiangtao
//
//  Created by xbmios on 2018/6/22.
//  Copyright © 2018年 shanhaijin. All rights reserved.
//

#import "MineViewController.h"
#import "MineFirstTableViewCell.h"
#import "MineSecondTableViewCell.h"
#import "MineLastTableViewCell.h"

#import "SettingViewController.h"
#import "MemberViewController.h"
#import "UserInformationViewController.h"
#import "VerticalListViewController.h"
#import "IntegralRecordViewController.h"
#import "FinancialRecordViewController.h"
#import "ModifyPayPasswordViewController.h"
#define KnormalBgHeight jisuan(460)
#define KlargeBgHeight jisuan(624)

static NSString *mineFirstCellID = @"mineFirstCellID";
static NSString *mineSecondCellID = @"mineSecondCellID";
static NSString *mineLastCellID = @"mineLastCellID";

static NSString *mineHeaderID = @"mineHeaderID";


@interface MineViewController ()<UIScrollViewDelegate, UICollectionViewDelegateFlowLayout, UITableViewDelegate,UITableViewDataSource>

//@property (strong, nonatomic) UICollectionView *personalCollectionView;
@property (strong, nonatomic) UITableView *personalTableView;

// 头部视图
@property (strong, nonatomic) UIView *headerView;

// 头像
@property (strong, nonatomic) UIImageView *iconIV;
// 用户昵称
@property (strong, nonatomic) UILabel *userNameL;

// 设置
@property (strong, nonatomic) UIButton *settingBtn;


@property (strong, nonatomic) NSArray *cellArr;

@property (strong, nonatomic) UserInfoModel *userInfoModel;

@property (nonatomic, copy) NSString *imageUrlString;
@property (nonatomic, copy) NSString *webUrlString;



@end

@implementation MineViewController


- (void)setUserInfoModel:(UserInfoModel *)userInfoModel {
    
    _userInfoModel = userInfoModel;
    
    [CommonUserInfo sharedInstance].userInfoModel = userInfoModel;
    
    
    if ([CommonUserInfo sharedInstance].isLogin) {
        
        self.userNameL.text = userInfoModel.user_name;


    }else {
        
        self.userNameL.text = @"未登录";
  
        
    }

    if (userInfoModel.user_photo.length > 0) {

        [self.iconIV sd_setImageWithURL:[NSURL URLWithString:userInfoModel.user_photo]];
        
//        self.iconIV.image = [CommonUserInfo sharedInstance].iconIV;

    }else {

        self.iconIV.image = [UIImage imageNamed:@"iconHeader"];

    }
    
    [self.personalTableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];

}

- (void)loadShareData {
    
    NSString *user_id = @"";
    
    if ([CommonUserInfo sharedInstance].user_id == nil) {
        user_id = @"0";
    }else {
        user_id = [CommonUserInfo sharedInstance].user_id;
    }
    
    NSString *string = [NSString stringWithFormat:@"{\"userid\" : \"%@\"}",[RSA encryptString:user_id publicKey:PublicKey]];
    
    WS(weakSelf);
    [PPNetworkHelper POST:@"index/Share/index" parameters:@{@"json":string} success:^(id responseObject) {
        if ([responseObject[@"code"] intValue] == 1) {
            weakSelf.imageUrlString = responseObject[@"data"][@"image2"];
            weakSelf.webUrlString = responseObject[@"data"][@"url2"];
            [weakSelf.personalTableView reloadData];
        }
    } failure:^(NSError *error) {
        
    }];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
 
    if (@available(iOS 11.0, *)) {
        
        self.personalTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    self.view.backgroundColor = Colorf2f2f2;
    

   

    [self.view addSubview:self.personalTableView];

    WS(weakSelf)
    [self.personalTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(weakSelf.view);
        make.bottom.mas_equalTo(weakSelf.view.mas_bottom).with.offset(-Height_NavBar);
    }];
    

    
    UIView *contentView = [[UIView alloc] init];
    contentView.backgroundColor = [UIColor whiteColor];
    [self.headerView addSubview:contentView];
    
    [contentView addSubview:self.iconIV];
    [contentView addSubview:self.userNameL];
    [contentView addSubview:self.settingBtn];

    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(weakSelf.headerView.mas_left);
        make.top.mas_equalTo(weakSelf.headerView.mas_top);
        make.width.mas_equalTo(WIDTH);
        make.bottom.mas_equalTo(weakSelf.headerView.mas_bottom).with.offset(-jisuan(20));
    }];

    [self.iconIV mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(contentView.mas_left).with.offset(jisuan(40));
        make.bottom.mas_equalTo(contentView.mas_bottom).with.offset(0);
        make.width.mas_equalTo(jisuan(90));
        make.height.mas_equalTo(jisuan(90));
    }];
    [self.userNameL mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(contentView.mas_left).with.offset(jisuan(170));
        make.centerY.mas_equalTo(weakSelf.iconIV.mas_centerY);
        
    }];
    
    [self.settingBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.mas_equalTo(contentView.mas_right).with.offset(-jisuan(40));
        make.centerY.mas_equalTo(weakSelf.iconIV.mas_centerY);
        make.width.mas_equalTo(jisuan(40));
        make.height.mas_equalTo(jisuan(40));
        
    }];

}


#pragma mark -昵称点击事件
- (void)userInformationGestureClick:(UIGestureRecognizer *)recognizer {
    
    NSLog(@"用户信息点击事件");
    
    if (![[CommonAction sharedInstance] isLoginWithParentVc:self]) {
        
        return;
    }
    
    UserInformationViewController *vc = [[UserInformationViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
    
}


#pragma mark -积分金额点击事件
- (void)integralClick:(UIGestureRecognizer *)recognizer {
    
    NSLog(@"积分金额点击事件");
    
    if (![[CommonAction sharedInstance] isLoginWithParentVc:self]) {
        
        return;
    }
    
    IntegralRecordViewController *vc = [[IntegralRecordViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
    
}

#pragma mark -奖励金额点击事件
- (void)incomeClick:(UIGestureRecognizer *)recognizer {
    
    NSLog(@"奖励金额点击事件");
    
    if (![[CommonAction sharedInstance] isLoginWithParentVc:self]) {
        
        return;
    }

    // 跳转h5
    WebViewController *webVctr = [[WebViewController alloc] init];
    if (self.webUrlString.length<1) {
        return;
    }
    webVctr.url = self.webUrlString;
    [self.navigationController pushViewController:webVctr animated:YES];

    
}

#pragma mark -进货资金点击事件
- (void)frozenClick:(UIGestureRecognizer *)recognizer {
    
    NSLog(@"进货资金点击事件");

    if (![[CommonAction sharedInstance] isLoginWithParentVc:self]) {
        
        return;
    }
    
    FinancialRecordViewController *vc = [[FinancialRecordViewController alloc] init];
    vc.type = 4;
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark -delegete\datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 3;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 1;
 
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MineFirstTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:mineFirstCellID];
    
    MineSecondTableViewCell *cell1 = [tableView dequeueReusableCellWithIdentifier:mineSecondCellID];
    
    MineLastTableViewCell *cell2 = [tableView dequeueReusableCellWithIdentifier:mineLastCellID];
    
    if (!cell) {
    
        cell = [[MineFirstTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:mineFirstCellID];
        
    }
    if (!cell1) {
        
        cell1 = [[MineSecondTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:mineSecondCellID];
        
    }
    if (!cell2) {
        
        cell2 = [[MineLastTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:mineLastCellID];
        
    }
    
    if (indexPath.section == 0) {
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.parentVC = self;
        cell.userinfoModel = self.userInfoModel;
        return cell;
        
    }else if (indexPath.section == 2){
        
        cell2.parentVC = self;
        cell2.lastArr = self.cellArr[1];
        cell2.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell2;
        
    }else {
        
        cell1.cellType = 2;
        cell1.parentVC = self;
        cell1.arr = self.cellArr[0];
        cell1.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell1;
        
    }

    
}


- (void)tapAvatarVieweererer {
    
    if (![[CommonAction sharedInstance] isLoginWithParentVc:self]) {
        
        return;
    }
    
    if (self.webUrlString.length < 1) {
        return;
    }

    
    WebViewController *wev = [[WebViewController alloc] init];
    wev.url = self.webUrlString;
    [self.navigationController pushViewController:wev animated:YES];
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (section == 1) {
        
        UIView *headerBgView = [[UIView alloc] init];
        headerBgView.backgroundColor = WhiteColor;
        
        UILabel *label = [[UILabel alloc] init];
        label.textColor = Color333333;
        label.textAlignment = NSTextAlignmentLeft;
        label.font = Font(24);
        label.frame = CGRectMake(jisuan(40), 0, jisuan(200), jisuan(94));
        [headerBgView addSubview:label];
        
        if (section == 1) {
            
            label.text = @"我的购买订单";
            
        }
        
        return headerBgView;
        
    }else if (section == 0){
        
        return self.headerView;
    }else {
        return nil;
    }

    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    CGFloat h = (IS_IPHONE_X || IS_IPHONE_Xr || IS_IPHONE_Xs || IS_IPHONE_Xs_Max) ? jisuan(172) : jisuan(150);
    
    if (section == 1) {
        
        return jisuan(94);
        
    }else if (section == 0) {
        
        return h;
    }else {
        return 0.001;
    }
    
    
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {

    return section == 2 ? 90+Margin : Margin;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        return jisuan(166);
        
    }else if (indexPath.section == 1) {
        
        return jisuan(138);
        
    }else {
        
        return jisuan(158)*2;
    }
 
    
}

#pragma mark -设置按钮点击事件
- (void)settingBtnClick:(UIButton *)btn {
    
    NSLog(@"设置按钮点击事件");
    
    if (![[CommonAction sharedInstance] isLoginWithParentVc:self]) {
        
        return;
    }
    
    SettingViewController *settingVC = [[SettingViewController alloc] init];
    
    [self.navigationController pushViewController:settingVC animated:YES];
    
}



#pragma mark -lazy
- (UIView *)headerView {
    
    if (!_headerView) {
        
        _headerView = [[UIView alloc] init];
        _headerView.backgroundColor = [UIColor colorWithHexString:@"F6F8FA"];
        
    }
    
    return _headerView;
}

- (UITableView *)personalTableView {
    
    if (!_personalTableView) {
        
        _personalTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        
        _personalTableView.delegate = self;
        _personalTableView.dataSource = self;
        
//        _personalTableView.bounces = NO;

        _personalTableView.showsVerticalScrollIndicator = NO;
        _personalTableView.showsHorizontalScrollIndicator = NO;
      
        _personalTableView.estimatedRowHeight = 0;
        _personalTableView.estimatedSectionHeaderHeight = 0;
        _personalTableView.estimatedSectionFooterHeight = 0;
        
        _personalTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        
    }
    
    return _personalTableView;
    
}


- (UIImageView *)iconIV {
    
    if (!_iconIV) {
        
        _iconIV = [[UIImageView alloc] init];
        _iconIV.contentMode = UIViewContentModeScaleToFill;
        _iconIV.image = [UIImage imageNamed:@"iconHeader"];
        
        _iconIV.layer.cornerRadius = jisuan(45);
        _iconIV.layer.masksToBounds = YES;
        
        _iconIV.userInteractionEnabled = YES;
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(userInformationGestureClick:)];
        [_iconIV addGestureRecognizer:tapGesture];
    }
    
    return _iconIV;
}
- (UILabel *)userNameL {
    
    if (!_userNameL) {
        
        _userNameL = [[UILabel alloc] init];
        _userNameL.textColor = [UIColor colorWithHexString:@"333333"];
        _userNameL.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:jisuan(36)];
        _userNameL.textAlignment = NSTextAlignmentLeft;
        
        _userNameL.text = @"未登录";
//        _userNameL.userInteractionEnabled = YES;
    }
    
    return _userNameL;
}



- (UIButton *)settingBtn {
    
    if (!_settingBtn) {
        
        _settingBtn = [[UIButton alloc] init];
        [_settingBtn setImage:[UIImage imageNamed:@"分组-1"] forState:UIControlStateNormal];
        [_settingBtn setImage:[UIImage imageNamed:@"分组-1"] forState:UIControlStateHighlighted];
        
        [_settingBtn addTarget:self action:@selector(settingBtnClick:) forControlEvents:UIControlEventTouchUpInside];
   
    }
    
    return _settingBtn;
}



- (NSArray *)cellArr {
    
    if (!_cellArr) {
        
        _cellArr = @[
                     @[
                         @{
                             
                             @"icon" : [UIImage imageNamed:@"shoppingNotPay"],
                             @"name" : @"我的订单"
                             },
                         @{
                             
                             @"icon" : [UIImage imageNamed:@"mineTaobaoBG"],
                             @"name" : @"淘宝订单"
                             },
                         
                         @{
                             
                             @"icon" : [UIImage imageNamed:@"jddd"],
                             @"name" : @"京东订单",
                             },
                         
                         @{
                             
                             @"icon" : [UIImage imageNamed:@"mineOtherOrderBG"],
                             @"name" : @"退款订单",
                             @"status" : @"1"
                             }
                         
                         ],
                     
                     @[
//                         @{
//                             
//                             @"icon" : [UIImage imageNamed:@"detail"],
//                             @"name" : @"积分明细"
//                             },
//                         @{
//                             
//                             @"icon" : [UIImage imageNamed:@"liuliangbi"],
//                             @"name" : @"趣豆明细"
//                             },
                         @{
                             
                             @"icon" : [UIImage imageNamed:@"financeRecord"],
                             @"name" : @"财务记录"
                             },

                         @{
                             
                             @"icon" : [UIImage imageNamed:@"payManage"],
                             @"name" : @"支付管理"
                             },
                         @{
                             
                             @"icon" : [UIImage imageNamed:@"passwordManage"],
                             @"name" : @"密码管理"
                             },
                         @{
                             
                             @"icon" : [UIImage imageNamed:@"addressBG"],
                             @"name" : @"我的地址"
                             },
                         @{
                             
                             @"icon" : [UIImage imageNamed:@"helpCenter"],
                             @"name" : @"常见问题"
                             },
                         @{
                             
                             @"icon" : [UIImage imageNamed:@"orderMarraa"],
                             @"name" : @"订单匹配"
                             }
//                         @{
//
//                             @"icon" : [UIImage imageNamed:@"orderMarraa"],
//                             @"name" : @"我的收藏"
//                             }
                         
                         ]
                     
                     ];
        
        
    }
    
    return _cellArr;
}

#pragma mark -设置
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.hidden = YES;
    
    __weak typeof(self) weakSelf = self;
    
    [self loadShareData];
    
    if ([CommonUserInfo sharedInstance].isLogin) {
        
        [[CommonAction sharedInstance] userVisitRecordWithRoute:@"我的"];

        [[CommonAction sharedInstance] getUserInfoWithBlock:^(id result) {
            
            weakSelf.userInfoModel = result;
              
        }];

        
    }else {
        
        self.userInfoModel = nil;
    }
    [TalkingData trackPageBegin:@"我的页"];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [TalkingData trackPageEnd:@"我的页"];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];    
}



@end
